package com.tensquare.test.spit.controller;

import com.tensquare.test.spit.pojo.Spit;
import com.tensquare.test.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/spit")
public class SpitController {
    @Autowired
    private SpitService spitService ;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "/thumbup/{spitId}",method = RequestMethod.PUT)
    public Result thumbup(@PathVariable String spitId){
        String userid ="111";
       if ( redisTemplate.opsForValue().get("thumbup_"+userid)!=null){
           return new Result(false, StatusCode.ERROR,"不能重复点赞");
       }


        spitService.thumbup(spitId);
        redisTemplate.opsForValue().set("thumbup_"+userid,1);
        return new Result(true, StatusCode.OK,"吐槽点赞成功");

    }


    @RequestMapping(method = RequestMethod.GET)
    public Result findAll(){
        System.out.println("进入findAll方法");
        List<Spit> all = spitService.findAll();
        System.out.println(all);

        return new Result(true, StatusCode.OK,"查询全部成功",spitService.findAll());
    }

    @RequestMapping(value = "/{spitId}",method = RequestMethod.GET)
    public Result findByid(@PathVariable String spitId){
        return new Result(true, StatusCode.OK,"查询成功",spitService.findById(spitId));
    }

   @RequestMapping(value = "/comment/{parentid}/{page}/{size}",method = RequestMethod.GET)
    public Result findByParentid(@PathVariable String parentid,@PathVariable int page ,@PathVariable int size){
        Page<Spit> pageData = spitService.findByParentId(parentid, page, size);

        //new PageResult<Spit>(long total, List<T> rows)：取得分页数据的总数以及内容
        PageResult<Spit> spitPageResult = new PageResult<>(pageData.getTotalElements(), pageData.getContent());

        return new Result(true, StatusCode.OK,"查询父类成功",spitPageResult);
    }

    @RequestMapping(value = "/{spitId}",method = RequestMethod.PUT)
    public Result updata(@RequestBody Spit spit,@PathVariable String spitId){
        spit.set_id(spitId);
        spitService.updata(spit);
        return new Result(true, StatusCode.OK,"更新成功");
    }

    @RequestMapping(method = RequestMethod.POST)
    public Result save(@RequestBody Spit spit){
        spitService.save(spit);
        return new Result(true, StatusCode.OK,"保存成功");
    }
    @RequestMapping(value = "/{spitId}",method = RequestMethod.DELETE)
    public Result delete(@PathVariable String spitId){
        spitService.delete(spitId);
        return new Result(true, StatusCode.OK,"删除成功");
    }
}
